// Promise 并行执行

function ajax(url) {
  return new Promise(function (resolver, reject) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.responseType = "json";
    xhr.onload = function () {
      if (this.status === 200) {
        resolver(this.response);
      } else {
        reject(new Error(this.statusText))
      }
    };

    xhr.send();
  })
}

let promiseAll = Promise.all([
  ajax("/api/users.json"),
  ajax("/api/users.json")
]);
// console.log(promiseAll);
promiseAll.then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
})

ajax("/api/urls.json")
  .then(res => {
    let urls = Object.values(res);
    const task = urls.map(url => ajax(url));
    return Promise.all(task);
  }).then(res => {
    console.log(res);
  });


const request = ajax("/api/posts.json");

const timeout = new Promise((resolver, reject) => {
  setTimeout(reject, 1500, "timeout")
  // setTimeout(reject, 1500, new Error("timeout"))
})

Promise.race([
  request, timeout
]).then(res => {
  console.log(res);
}).catch(err => {
  console.log(err);
})